package top.roadvast.rabbitmq.utils;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @Author 郭泽鹏
 * @Date 2021/12/25 22:32
 * @Version 1.0
 * @Description rabbitmq连接工具类
 */
public class RabbitmqUtil {
    private static ConnectionFactory connectionFactory;
    static {
        //创建连接工厂，设置连接信息
        connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("192.168.47.101");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("roadvast");
        connectionFactory.setPassword("123456");
    }

    /*
     * 与rabbitmq服务器建立连接,
     * rabbitmq服务器端使用的是nio,会复用tcp连接,
     * 并开辟多个信道与客户端通信
     * 以减轻服务器端建立连接的开销
     */
    public static Connection getConnection() {
        Connection connection = null;
        try {
            connection = connectionFactory.newConnection();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
        return connection;
    }

    /**
     * 关闭连接
     * @param connection 连接
     * @param channel 通道
     */
    public static void closeConnection(Connection connection, Channel channel) {
        try {
            channel.close();
            connection.close();
        } catch (IOException | TimeoutException e) {
            e.printStackTrace();
        }
    }
}
